import axios, { AxiosError } from 'axios'
import { showLoading, hideLoading } from './loadingSVG'
import { ResType } from '@/types/api'
import { message } from './AntdGlobal'

const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 5000, // 请求超时，单位毫秒
  timeoutErrorMessage: '请求超时，请稍后再试！',
  withCredentials: true // 允许跨域
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    if (config.showLoading) showLoading()
    const token = localStorage.getItem('token')
    if (token) config.headers.Authorization = 'Token::' + token
    return { ...config }
  },
  (error: AxiosError) => {
    console.log('请求拦截器中出现异常：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  // (response: AxiosResponse): AxiosResponse<ResType> | Promise<AxiosResponse<any, any>> => {
  response => {
    const data = response.data
    hideLoading()
    // if (data.code === 500001) {
    //   message.error(data.msg)
    //   localStorage.removeItem('token')
    //   location.href = '/login'
    // } else if (data.code != 0) {
    //   if (data.msg) message.error(data.msg)
    //   else console.log(`得到的响应结果code:${data.code}，提示文案msg:${data.msg}`)
    //   return Promise.reject(data)
    // }
    const tmp = data as ResType
    if (tmp.success) return data
    if (response.config.showError) message.error(data.msg)
    return Promise.reject(data)
  },
  err => {
    hideLoading()
    console.log('响应拦截器中出现异常：', err)
    message.error(err.message)
    return Promise.reject(err.message)
  }
)

interface IConfig {
  showLoading?: boolean
  showError?: boolean
}
export default {
  get<T>(url: string, params?: unknown, options: IConfig = { showLoading: true, showError: true }): Promise<T> {
    return instance.get(url, { params, ...options })
  },
  post<T>(url: string, params?: unknown, options: IConfig = { showLoading: true, showError: true }): Promise<T> {
    return instance.post(url, params, options)
  }
}
